<template>
	<view class="cart-container">
		<!-- 顶部导航栏 -->
		<view class="cart-nav">
			<view class="nav-left">
				<checkbox :checked="allChecked" @change="handleAllCheck" class="all-check" />
				<text class="nav-title">我的购物车</text>
			</view>
			<view class="nav-right" @click="handleEditMode">
				<text>{{ isEditMode ? '完成' : '编辑' }}</text>
			</view>
		</view>

		<!-- 购物车 -->
		<view class="cart-list" v-if="!isLoading">
			<!-- 空购物车状态 -->
			<view class="empty-cart" v-if="!cartList.length">
				<image src="/static/images/empty-cart.png" mode="widthFix" class="empty-img"></image>
				<text class="empty-text">您的购物车还是空的~</text>
				<button class="go-shop-btn" @click="goToHome">去逛逛</button>
			</view>

			<!-- 商家分组项 -->
			<view class="shop-cart-item" v-else v-for="(shopCart, shopIndex) in cartList" :key="shopCart.cartId">
				<!-- 商家信息栏 -->
				<view class="shop-header" @click="goToShopDetail(shopCart.businessId)">
					<view class="shop-check">
						<checkbox :checked="shopCart.isShopChecked" @change="(e) => handleShopCheck(e, shopIndex)" />
					</view>
					<view class="shop-info">
						<text class="shop-name">{{ shopCart.shopName || `商家${shopCart.businessId}` }}</text>
						<!-- 商家头像 -->
						<image v-if="shopCart.shopAvatar" :src="shopCart.shopAvatar" mode="aspectFill"
							class="shop-avatar"></image>
					</view>
					<view class="shop-operate" v-if="isEditMode">
						<text @click.stop="handleClearShopCart(shopCart.cartId)">清空</text>
					</view>
				</view>

				<!-- 商家下的商品列表 -->
				<view class="product-list">
					<view class="product-item" v-for="(product, prodIndex) in shopCart.items" :key="product.id">
						<!-- 商品复选框 -->
						<checkbox :checked="product.checked" @change="(e) => handleItemCheck(e, shopIndex, prodIndex)"
							class="prod-check" />

						<!-- 商品图片 -->
						<image :src="product.productImage || '/static/images/default-prod.png'" mode="aspectFill"
							class="prod-img"></image>

						<!-- 商品信息 -->
						<view class="prod-info">
							<text class="prod-name">{{ product.productName }}</text>
							<text class="prod-desc" v-if="product.productDescription">
								{{ product.productDescription.length > 20 ? `${product.productDescription.slice(0,20)}...` : product.productDescription }}
							</text>
							<view class="prod-price-row">
								<text class="prod-price">¥{{ (product.productPrice || 0).toFixed(2) }}</text>
								<text class="prod-subtotal" v-if="!isEditMode">
									¥{{ (product.productPrice * product.number).toFixed(2) }}
								</text>
							</view>
						</view>

						<!-- 商品操作（数量/删除） -->
						<view class="prod-operate">
							<view class="quantity-control" v-if="!isEditMode">
								<button class="btn-minus" @click="handleProdMinus(shopCart.cartId, product.productId)"
									:disabled="product.number <= 1">-</button>
								<text class="quantity">{{ product.number }}</text>
								<button class="btn-plus"
									@click="handleProdPlus(shopCart.cartId, product.productId)">+</button>
							</view>
							<view class="delete-btn" v-if="isEditMode"
								@click="handleProdDelete(shopCart.cartId, product.productId)">
								<uni-icons type="trash" size="24" color="#ff4444"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载中状态 -->
		<view class="loading-tip" v-if="isLoading">
			<uni-load-more size="24" color="#007aff"></uni-load-more>
			<text>加载购物车...</text>
		</view>

		<!-- 底部合计栏-->
		<view class="cart-footer" v-if="cartList.length && !isLoading">
			<view class="footer-left">
				<text class="selected-count">已选 {{ selectedCount }} 件</text>
			</view>
			<view class="footer-right">
				<view class="total-amount">
					<text class="amount-label">合计：</text>
					<text class="amount-value">¥{{ selectedAmount.toFixed(2) }}</text>
				</view>
				<button class="checkout-btn" @click="handleCheckout" :disabled="selectedCount === 0">
					{{ isEditMode ? '删除选中' : '去结算' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import uniIcons from '@/components/uni-icons/uni-icons.vue'

	import cartApi from '@/api/product/cart.js'

	export default {
		components: {
			uniIcons,

		},
		data() {
			return {
				cartList: [], // 购物车列表（按商家分组）
				allChecked: false, // 全选状态
				selectedCount: 0, // 已选商品总数
				selectedAmount: 0, // 已选商品总价
				isLoading: true, // 加载状态
				isEditMode: false // 编辑模式（切换“编辑/完成”）
			}
		},
		computed: {
			// 从Vuex获取用户ID
			...mapGetters('user', ['userId'])
		},
		onShow() {
			// 页面显示时刷新购物车
			this.getCartData()
		},
		methods: {
			/**
			 * 获取购物车数据（按用户ID）
			 */
			async getCartData() {
				if (!this.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}

				this.isLoading = true
				try {
					// 调用API获取用户所有购物车
					const res = await cartApi.getAllCartByUser(this.userId)
					if (res.code === 200) {
						// 格式化购物车数据
						const cartData = Array.isArray(res.data) ? res.data : [res.data]
						// 补充商家选中状态、商品选中状态
						this.cartList = cartData.map(shopCart => ({
							...shopCart,
							isShopChecked: false, // 商家全选状态
							items: (shopCart.items || []).map(prod => ({
								...prod,
								checked: false // 商品选中状态
							}))
						}))
						// 初始化选中状态（默认全不选）
						this.calculateSelected()
					} else {
						uni.showToast({
							title: res.msg || '获取购物车失败',
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('获取购物车失败：', e)
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},

			/**
			 * 计算已选商品数量和总价
			 */
			calculateSelected() {
				let count = 0
				let amount = 0

				this.cartList.forEach(shopCart => {
					shopCart.items.forEach(prod => {
						if (prod.checked) {
							count += prod.number
							amount += Number(prod.productPrice) * prod.number
						}
					})

					// 更新商家选中状态（所有商品选中则商家选中）
					const allProdChecked = shopCart.items.every(prod => prod.checked)
					shopCart.isShopChecked = allProdChecked
				})

				// 更新全选状态（所有商家选中则全选）
				this.allChecked = this.cartList.every(shopCart => shopCart.isShopChecked)
				// 更新已选数据
				this.selectedCount = count
				this.selectedAmount = amount
			},

			/**
			 * 全选/取消全选
			 */
			handleAllCheck(e) {
				const isChecked = e.detail.value[0]
				this.allChecked = isChecked

				// 同步所有商家和商品的选中状态
				this.cartList.forEach(shopCart => {
					shopCart.isShopChecked = isChecked
					shopCart.items.forEach(prod => {
						prod.checked = isChecked
					})
				})

				// 重新计算总价
				this.calculateSelected()
			},

			/**
			 * 商家全选/取消全选
			 */
			handleShopCheck(e, shopIndex) {
				const isChecked = e.detail.value[0]
				const targetShop = this.cartList[shopIndex]

				// 同步该商家下所有商品的选中状态
				targetShop.isShopChecked = isChecked
				targetShop.items.forEach(prod => {
					prod.checked = isChecked
				})

				// 重新计算总价和全选状态
				this.calculateSelected()
			},

			/* 单个商品选中/取消选中 */
			handleItemCheck(e, shopIndex, prodIndex) {
				const isChecked = e.detail.value[0]
				const targetProd = this.cartList[shopIndex].items[prodIndex]


				targetProd.checked = isChecked
				this.calculateSelected()
			},

			/* 商品数量减少*/
			async handleProdMinus(cartId, productId) {
				try {
					await cartApi.operateCartItem({
						cartId,
						productId,
						operationType: 'REDUCE' // 减少操作
					})
					// 刷新数据
					this.getCartData()
				} catch (e) {
					uni.showToast({
						title: '减少失败，请重试',
						icon: 'none'
					})
				}
			},

			/*商品数量增加 */
			async handleProdPlus(cartId, productId) {
				try {
					await cartApi.operateCartItem({
						cartId,
						productId,
						operationType: 'ADD'
					})
					this.getCartData()
				} catch (e) {
					uni.showToast({
						title: '增加失败，请重试',
						icon: 'none'
					})
				}
			},

			/*删除单个商品*/
			async handleProdDelete(cartId, productId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await cartApi.operateCartItem({
									cartId,
									productId,
									operationType: 'DELETE' // 删除操作
								})
								uni.showToast({
									title: '删除成功'
								})
								// 刷新购物车数据
								this.getCartData()
							} catch (e) {
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			/*清空商家购物车*/
			async handleClearShopCart(cartId) {
				uni.showModal({
					title: '提示',
					content: '确定要清空该商家的购物车吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await cartApi.clearCart(cartId)
								uni.showToast({
									title: '清空成功'
								})
								// 刷新购物车数据
								this.getCartData()
							} catch (e) {
								uni.showToast({
									title: '清空失败，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			/* 切换编辑模式*/
			handleEditMode() {
				this.isEditMode = !this.isEditMode
				if (this.isEditMode) {
					this.allChecked = false
					this.cartList.forEach(shopCart => {
						shopCart.isShopChecked = false
						shopCart.items.forEach(prod => {
							prod.checked = false
						})
					})
					this.calculateSelected()
				}
			},

			/**去结算/删除选中*/
			handleCheckout() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					})
					return
				}

				if (this.isEditMode) {
					this.batchDeleteSelected()
				} else {
					uni.navigateTo({
						url: `/pages/order/checkout?selectedData=${encodeURIComponent(JSON.stringify(this.getSelectedData()))}`
					})
				}
			},

			/*获取选中商品数据*/
			getSelectedData() {
				const selectedData = []
				this.cartList.forEach(shopCart => {
					const selectedProds = shopCart.items.filter(prod => prod.checked)
					if (selectedProds.length) {
						selectedData.push({
							cartId: shopCart.cartId,
							businessId: shopCart.businessId,
							shopName: shopCart.shopName,
							products: selectedProds
						})
					}
				})
				return selectedData
			},

			/*批量删除选中商品*/
			async batchDeleteSelected() {
				const selectedData = this.getSelectedData()
				try {
					for (const shop of selectedData) {
						for (const prod of shop.products) {
							await cartApi.operateCartItem({
								cartId: shop.cartId,
								productId: prod.productId,
								operationType: 'DELETE'
							})
						}
					}
					uni.showToast({
						title: '删除选中成功'
					})
					this.getCartData()
				} catch (e) {
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					})
				}
			},

			/* 跳转到商家详情页*/
			goToShopDetail(businessId) {
				if (!businessId) return
				uni.navigateTo({
					url: `/pages/shop/shopDetail?shopId=${businessId}`
				})
			},

			/*空购物车跳转首页*/
			goToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style lang="scss">
	.cart-container {
		min-height: 100vh;
		background-color: #f5faf9;
		padding-bottom: 120rpx;
	}

	/* 顶部导航 */
	.cart-nav {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 90rpx;
		padding: 0 30rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 8rpx rgba(0, 120, 107, 0.1);

		.nav-left {
			display: flex;
			align-items: center;
			gap: 15rpx;

			.all-check {
				transform: scale(1.2);
				color: #26a69a;
			}

			.nav-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #00796b;
			}
		}

		.nav-right {
			font-size: 28rpx;
			color: #00796b;
			padding: 10rpx 20rpx;
			border-radius: 20rpx;
			background-color: #e0f2f1;
		}
	}

	/* 购物车列表 */
	.cart-list {
		padding: 20rpx;
	}

	/* 空购物车 */
	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 0;

		.empty-img {
			width: 240rpx;
			margin-bottom: 30rpx;
		}

		.empty-text {
			font-size: 28rpx;
			color: #888;
			margin-bottom: 40rpx;
		}

		.go-shop-btn {
			background-color: #26a69a;
			color: #fff;
			font-size: 28rpx;
			padding: 15rpx 60rpx;
			border-radius: 40rpx;
		}
	}

	/* 商家购物车项 */
	.shop-cart-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 120, 107, 0.1);
		overflow: hidden;
	}

	/* 商家头部 */
	.shop-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #e0f2f1;

		.shop-check {
			margin-right: 20rpx;

			checkbox {
				transform: scale(1.1);
				color: #26a69a;
			}
		}

		.shop-info {
			flex: 1;
			display: flex;
			align-items: center;
			gap: 15rpx;

			.shop-name {
				font-size: 28rpx;
				font-weight: 500;
				color: #00796b;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.shop-avatar {
				width: 50rpx;
				height: 50rpx;
				border-radius: 50%;
			}
		}

		.shop-operate {
			font-size: 26rpx;
			color: #ff4444;
			padding: 5rpx 15rpx;
			border-radius: 15rpx;
			background-color: #fff8f8;
		}
	}

	/* 商品列表 */
	.product-list {
		padding: 20rpx 30rpx;
	}

	/* 商品项 */
	.product-item {
		display: flex;
		align-items: center;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		.prod-check {
			margin-right: 20rpx;
			transform: scale(1.1);
			color: #26a69a;
		}

		.prod-img {
			width: 120rpx;
			height: 120rpx;
			border-radius: 10rpx;
			margin-right: 20rpx;
			background-color: #f5f5f5;
		}

		.prod-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
			gap: 10rpx;

			.prod-name {
				font-size: 26rpx;
				color: #333;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}

			.prod-desc {
				font-size: 22rpx;
				color: #888;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.prod-price-row {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.prod-price {
					font-size: 26rpx;
					color: #f44336;
					font-weight: 500;
				}

				.prod-subtotal {
					font-size: 24rpx;
					color: #333;
				}
			}
		}

		.prod-operate {
			display: flex;
			align-items: center;
			gap: 20rpx;

			.quantity-control {
				display: flex;
				align-items: center;
				gap: 15rpx;

				.btn-minus,
				.btn-plus {
					width: 40rpx;
					height: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #f5f5f5;
					border-radius: 50%;
					font-size: 28rpx;
					color: #333;
				}

				.btn-minus:disabled {
					background-color: #eee;
					color: #ccc;
				}

				.quantity {
					font-size: 24rpx;
					color: #333;
					width: 50rpx;
					text-align: center;
				}
			}

			.delete-btn {
				color: #ff4444;
			}
		}
	}

	/* 加载中 */
	.loading-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
		color: #4db6ac;
		font-size: 28rpx;
		gap: 20rpx;
	}

	/* 底部合计栏 */
	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 120rpx;
		padding: 0 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 120, 107, 0.1);

		.footer-left {
			.selected-count {
				font-size: 26rpx;
				color: #333;
			}
		}

		.footer-right {
			display: flex;
			align-items: center;
			gap: 30rpx;

			.total-amount {
				display: flex;
				align-items: center;
				gap: 10rpx;

				.amount-label {
					font-size: 26rpx;
					color: #333;
				}

				.amount-value {
					font-size: 32rpx;
					color: #f44336;
					font-weight: 600;
				}
			}

			.checkout-btn {
				width: 200rpx;
				height: 70rpx;
				background-color: #26a69a;
				color: #fff;
				font-size: 28rpx;
				border-radius: 35rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.checkout-btn:disabled {
				background-color: #b2dfdb;
				color: #fff;
			}
		}
	}
</style>